# cocoa bridge
from Foundation import *
from AppKit import *
from ScriptingBridge import SBApplication

# standard modules
import os

from FileNode import FileNode
from helpers import log

### custom third party applications
class ThirdPartyApp(object):
	app = None
	name = ""
	sel = []
	
	def getSelection(self):
		return self.app.selection()
	
	def selectionChanged(self):
		oldSel = self.sel
		self.sel = self.getSelection()
		if oldSel != self.sel:
			return True

	def getNodes(self):
		return [FileNode.alloc().initWithURLStr_(x.URL()) for x in self.sel]
	


class AppFinder(ThirdPartyApp):
	def __init__(self):
		self.name = "Finder"
		self.app = SBApplication.applicationWithBundleIdentifier_("com.apple.Finder")
	
	def getSelection(self):
		return self.app.selection().get()


import iPhotoHelper
class AppIPhoto(ThirdPartyApp):
	def __init__(self):
		self.name = "Preview"
		self.app = SBApplication.applicationWithBundleIdentifier_("com.apple.iPhoto")
		
	def getNodes(self):
		okPhotos = []
		for photo in self.sel:
			try:
				p = iPhotoHelper.IPhotoNode(photo)
				okPhotos.append(p)
		
			except Exception, e:
				log(e)
		
		nodes=[]
		for x in okPhotos:
			node = x.fileNode()

			# grab keys
			if node.keys is None or node.keys == []:
				try:
					node.setKeys_(x.keywordArray + filter(lambda k: not k.startswith("["), x.comment.split()))
				except Exception,e:
					log("couldnt set keys: ",e)
			nodes.append(node)
		return nodes


class AppPreview(ThirdPartyApp):
	def __init__(self):
		self.name = "Preview"
		try:
			self.app = SBApplication.applicationWithBundleIdentifier_("com.apple.Preview")
		except Exception:
			log("failed to bind to preview - trying the ugly hack...")
			os.system("defaults write com.apple.Preview NSAppleScriptEnabled -bool YES")
			self.app = SBApplication.applicationWithBundleIdentifier_("com.apple.Preview")
			
